package com.domain.controller;

import com.domain.common.AppLogger;
import com.domain.common.Comments;
import com.domain.common.Const;
import com.domain.common.Result;
import com.domain.pojo.SmsCode;
import com.domain.pojo.Users;
import com.domain.service.LoginService;
import com.domain.service.RedisService;
import com.domain.service.SmsCodeService;
import com.domain.service.SmsService;
import com.domain.utils.NotNullUtils;
import com.domain.utils.RandomUtils;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录 注册控制器
 */
@Controller
@RequestMapping("/login")
public class LoginController {
    /**
     * 日志
     */
    private static Logger logger = AppLogger.getLogger(LoginController.class.getSimpleName(), Level.INFO.toString(), true);

    @Autowired
    private SmsService smsService;

    @Autowired
    private LoginService loginService;

    @Autowired
    private RedisService redisService;

    /**
     * 获取短信验证码(阿里短信)
     *
     * @param phoneNum //手机号码
     */
    @RequestMapping(value = "/getsmsCode", method = RequestMethod.POST)
    @ResponseBody
    public Result getsmsCode(String phoneNum) {
        try {
            return smsService.sendMessage(phoneNum, "7676");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("短信验证码获取失败");
        }
    }


    /**
     * 获取 个人标签列表
     *
     * @return
     */
    @RequestMapping(value = "/getUserLable", method = RequestMethod.POST)
    @ResponseBody
    public Result getUserLable() {
        try {
            return loginService.getUserLable();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("系统错误");
        }
    }

    /**
     * 获取行业标签列表
     *
     * @return
     */
    @RequestMapping(value = "/getUserIndustrysList", method = RequestMethod.POST)
    @ResponseBody
    public Result getUserIndustrysList() {
        try {
            return loginService.getUserIndustrysList();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("系统错误");
        }
    }

    /**
     * 注册验证
     *
     * @param phoneNumber
     * @param
     * @param
     * @return
     */
    @RequestMapping(value = "/checkRegister", method = RequestMethod.POST)
    @ResponseBody
    public Result checkPhone(String phoneNumber, String smsCode, HttpServletRequest request) {
        try {
            logger.info("phoneNumber:::::::::::::" + phoneNumber);
            logger.info("smsCode::::::::" + smsCode);
            if (!smsService.checkIsCorrectCode(phoneNumber, smsCode)) {
                return Result.publicResult(Comments.SMSCODE_FAIL, "验证码错误");
            } else if (redisService.getValue(phoneNumber) == null) {
                return Result.publicResult(Comments.SMSCODE_CHECK, "验证码已过期！");
            }
            //验证手机号是否注册
            int resultCount = loginService.checkPhone(phoneNumber);
            Map<String, Object> maps = new HashMap<>();
            if (resultCount > 0) {
                maps = loginService.checklogin(phoneNumber, request);
            } else {
                return Result.publicResult(Comments.ILLEGAL_ARGUMENT, "请注册");
            }
            return Result.success("操作成功", maps);

        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("系统错误");
        }
    }


    /**
     * 注册
     *
     * @param phoneNumber   电话号码
     * @param name          真实姓名
     * @param gender        性别（1 男  2 女）
     * @param birthday      生日
     * @param city          城市名称
     * @param industry      职业
     * @param personalLabel 个人标签
     * @param headImage     头像
     * @param request
     * @return
     */
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    @ResponseBody
    public Result register(
            String phoneNumber,
            String name,
            String gender,
            String birthday,
            String city,
            String industry,
            String personalLabel,
            String headImage,
            HttpServletRequest request) {
        try {
            Map<String, Object> maps = loginService.saveUser(phoneNumber, name, gender, birthday, city, industry, personalLabel, headImage, request);
            return Result.success("操作成功", maps);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("系统错误");
        }
    }

    /**
     * 退出登录
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/returnLogin", method = RequestMethod.POST)
    @ResponseBody
    public Result returnLogin(String userToken, HttpServletRequest request) {
        try {
            return loginService.outLogin(request);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("系统错误");
        }

    }

    /**
     * 注销
     *
     * @param userToken
     * @param request
     * @return
     */
    @RequestMapping(value = "/userCancellation", method = RequestMethod.POST)
    @ResponseBody
    public Result userCancellation(String userToken, String userId, HttpServletRequest request) {
        try {
            Users users = (Users) request.getSession().getAttribute(Const.CURRENT_USER);
            if (!NotNullUtils.isNotNullObject(users) || !users.getSpareOne().equals(userToken)) {
                return Result.publicResult(Comments.NEED_LOGIN, "请登录");
            }
            return loginService.userCancellation(userId);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("系统错误");
        }

    }

    /**
     * 马甲包测试登陆
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public Result login(String phoneNum, String password, HttpServletRequest request) {
        try {
            return loginService.login(phoneNum, password);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("系统错误");
        }

    }


}
